package com.pgy.backend.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

/**
 * @author 86159
 * @description 定时任务，用于设定时间保存定期数据库数据
 * @create 2023/12/19 14:37
 */
@Service
public class endTask {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final String YEAR = String.valueOf(LocalDate.now().getYear());


    //每年5月
    // @Scheduled(cron = "0 0 22 15 5 ? ")
    //每年10月15号下午22时整运行
    @Scheduled(cron = "0 0 22 15 10 ? ")
    //@Scheduled(cron = "0 39 * * * ? ")
    private void createTable(){
        try {
            jdbcTemplate.execute(tableExistsSql("evaluate_records"));
            jdbcTemplate.execute(sqlCreate("evaluate_records"));
            // jdbcTemplate.execute(sqlCreate("evaluate_records"));
            System.out.println("数据库表——evaluate_records_" + YEAR + "创建成功");
        } catch (Exception e) {
            e.printStackTrace();
        }try {
            jdbcTemplate.execute(tableExistsSql("grade_rule"));
            jdbcTemplate.execute(sqlCreate("grade_rule"));
            System.out.println("数据库表——grade_rule_" + YEAR + "创建成功");
        }catch (Exception e){
            e.printStackTrace();
        }try {
            jdbcTemplate.execute(tableExistsSql("pointer"));
            jdbcTemplate.execute(sqlCreate("pointer"));
            System.out.println("数据库表——pointer_" + YEAR + "创建成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * @description 统一生成建表语句
     * @param tableName——传入数据库名 bak_name_time
     * @return 返回建库语句
     */
    private String sqlCreate(String tableName){
        return "create table " + "bak_" + tableName + "_" + YEAR + " select * from " + tableName;
    }

    /**
     * @description 统一生成建表前检查语句，默认数据库不应该存在
     * @param tableName
     * @return
     */
    private String tableExistsSql(String tableName){
        return "drop table if exists " + "bak_" + tableName + "_" + YEAR;
    }

    /**
     * @description 生成数据库删除语句
     * @param tableName
     * @return
     */
    private String tableDelete(String tableName){
        return "truncate from " + tableName;
    }


}
